$(window).ready(function() {

    var places = [];
    places.push({ name: 'The Home Depot', sells: ['light bulb', 'wrench'], schedule: {} });
    places.push({ name: 'A&P', sells: ['tomatoes'], schedule: {} });
    places.push({ name: 'Guitar Center', sells: ['guitar'], schedule: {} });

    var tasks = [];
    tasks.push({ action: 'buy', item: 'wrench', before: 'April 25, 2012' });
    tasks.push({ action: 'buy', item: 'tomatoes', before: 'April 25, 2012' });
    tasks.push({ action: 'call', phone: 'John', before: 'April 30, 2012' });
    tasks.push({ action: 'buy', item: 'guitar', after: 'April 19, 2012' });

    //var mapsApiKey = 'AIzaSyAUkWFq8F3fi4hWvZ3vkRrlXcy53e57l2Q';
    var map = new google.maps.Map($('#map').get(0), {
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var renderPlan = function(plan) {
        var bounds = new google.maps.LatLngBounds();

        $.each(plan.steps, function(_, step) {
            var li = $('#list').append('<li></li>').children(':last');
            li.data('step', step);

            li.text(step.time.toPrettyString() + ', ' + step.action + ' ' + step.item);
            if (step.place) {
                li.text(li.text() + ' at ' + step.place.name + ' (' + step.place.address + ')');
            }

            if (step.place && step.place.geolocation) {
                var l = step.place.geolocation;
                var latlng = new google.maps.LatLng(l.latitude, l.longitude);
                new google.maps.Marker({
                    map: map,
                    position: latlng
                });
                bounds.extend(latlng);
            }

            li.click(function() {
                var step = $(this).data('step');
                if (step.place) {
                    var l = step.place.geolocation;
                    var latlng = new google.maps.LatLng(l.latitude, l.longitude);
                    map.panTo(latlng);
                }
            });

        });

        map.fitBounds(bounds);
    };

    var locationService = new LocationService();

    locationService.getCurrentPosition(function(position) {
        var blueMarker = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
        var latlng = new google.maps.LatLng(position.latitude, position.longitude);
        new google.maps.Marker({
            map: map,
            position: latlng,
            icon: blueMarker
        });
    });

    var locationPredictor = new LocationPredictor({
        locationService: locationService
    });

    var planner = new Planner({
        locationPredictor: locationPredictor,
        locationService: locationService
    });

    planner.setPlaces(places);
    planner.setTasks(tasks);
    planner.computeSingleStagePlan(renderPlan);
});
